package com.ncloud.param.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.RedisUtils;
import com.ncloud.param.entity.TableDict;
import com.ncloud.param.mapper.TableDictMapper;
import com.ncloud.param.service.TableDictService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class TableDictServiceImpl implements TableDictService {
	@Resource
	private TableDictMapper mapper;
	@Autowired
	private RedisUtils redisUtils;

	private static final Long expireTime= 7*24*60*60L;

	public JSONArray getDictList(JSONObject json){
		if(!json.containsKey("code"))
			throw new UserException("2001", "传入参数有误");
		String code = json.getString("code");
		String suffix = json.getString("suffix");
		JSONArray array = new JSONArray();
		if(StringUtils.isNoneBlank(suffix))
			array = getDisctByCode(code+"_"+suffix);
		if(array==null || array.isEmpty())
			array = getDisctByCode(code);
		return array;
	}

	private JSONArray getDisctByCode(String code) {
		String key = "dict_code_"+code;
		if(redisUtils.exists(key)){
			JSONArray info = redisUtils.getBean(key,JSONArray.class);
			return info;
		}else{
			List<TableDict> dicts = mapper.getDictList(code);
			JSONArray array = JSON.parseArray(JSON.toJSONString(dicts));
			if(dicts!=null && dicts.size()>0){
				redisUtils.set(key,array,expireTime);
			}
			return array;
		}
	}

	@Override
	public String getExplainByValue(JSONObject json) {
		if(!json.containsKey("code") || !json.containsKey("value"))
			throw new UserException("2001", "传入参数有误");
		String code = json.getString("code");
		String value = json.getString("value");
		TableDict dict = mapper.getTableDict(code,value );
		if(dict != null)
			return dict.getLabel();
		return null;
	}
}
